package view;

import com.googlecode.charts4j.GChart;
import util.FontLoader;
import util.ImageLoader;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.net.URL;

public class ChartView extends JLabel {

    public ChartView() {
        super();
    }

    public ChartView(String label) {
        super(label);
    }

    public void showChart (final GChart chart, Dimension size) {
        chart.setMargins(8,8,8,8);
        setIcon(ImageLoader.getImage("loading.gif"));
        setHorizontalAlignment(SwingConstants.CENTER);
        setAlignmentX(Component.CENTER_ALIGNMENT);
        setPreferredSize(size);
        Font f = FontLoader.getFont(FontLoader.OPENSANS_BOLD);
        f = f.deriveFont(26f);
        setForeground(java.awt.Color.DARK_GRAY);
        setFont(f);

        setVerticalTextPosition(JLabel.TOP);
        setHorizontalTextPosition(JLabel.CENTER);

        SwingWorker<ImageIcon, Object> sw = new SwingWorker<ImageIcon, Object>() {
            public ImageIcon doInBackground() {
                try {
                    BufferedImage img = ImageIO.read(new URL(chart.toURLString()));
                    return new ImageIcon(img);
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }

            protected void done() {
                try {
                    setIcon(get());
                    revalidate();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        sw.execute();
    }
}
